﻿Imports ACompany.OrderProcessing.Model
Imports ACompany.OrderProcessing.Infrastructure
Imports ACompany.OrderProcessing.NhibernateRepository

Public Class CustomerService
    Implements ICustomerService

    Private _CustomerRepository As ICustomerRepository
    Private _UnitOfWork As IUnitOfWork

    Public Sub New(ByVal CustomerRepository As ICustomerRepository, ByVal UnitOfWork As IUnitOfWork)
        Me._CustomerRepository = CustomerRepository
        Me._CustomerRepository.Inject(UnitOfWork)
        Me._UnitOfWork = UnitOfWork
    End Sub

    Public Function FindAll() As System.Collections.Generic.List(Of Model.Customer) Implements Model.ICustomerService.FindAll
        Return _CustomerRepository.FindAll
    End Function

    Public Sub Save(ByVal Customer As Model.Customer) Implements Model.ICustomerService.Save
        If Customer.GetBrokenRules.Count > 0 Then
            Dim brokenRules As String = BuildErrorListFrom(Customer)

            Throw New InvalidOperationException( _
                String.Format("The Customer is not in a valid state to be persisted. {0}", brokenRules))
        Else
            _CustomerRepository.Save(Customer)
            _UnitOfWork.Commit()
        End If

    End Sub

    Private Function BuildErrorListFrom(ByVal Customer As Customer) As String

        Dim brokenRulesList As New Text.StringBuilder

        For Each brokenRule As BrokenRule In Customer.GetBrokenRules
            brokenRulesList.Append(brokenRule.Rule)
            brokenRulesList.Append(Environment.NewLine)
        Next

        Return brokenRulesList.ToString

    End Function

    Public Function FindBy(ByVal Id As Guid) As Model.Customer Implements Model.ICustomerService.FindBy
        Return _CustomerRepository.FindBy(Id)
    End Function

    Public Sub Remove(ByVal Customer As Model.Customer) Implements Model.ICustomerService.Remove
        ' Check if this Customer has any orders
        ' Lazy load is used here
        If Customer.Orders.Count = 0 Then
            _CustomerRepository.Remove(Customer)
            _UnitOfWork.Commit()
        Else
            Throw New ApplicationException("Cannot delete a customer that has orders")
        End If
    End Sub
End Class
